﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 进制转换
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            if (int.TryParse(txtDecimal.Text, out int decimalNum) && int.TryParse(txtBase.Text, out int baseNum))
            {
                if (baseNum >= 2 && baseNum <= 16)
                {
                    string result = DecimalToBase(decimalNum, baseNum);
                    txtResult.Text = result;
                }
                else
                {
                    MessageBox.Show("转换进制应在2-16之间！", "提示");
                }
            }
            else
            {
                MessageBox.Show("请输入有效的数字！", "提示");
            }
        }

        private string DecimalToBase(int decimalNum, int baseNum)
        {
            if (decimalNum == 0)
            {
                return "0";
            }
            string result = "";
            while (decimalNum > 0)
            {
                int remainder = decimalNum % baseNum;
                char digit;
                if (remainder < 10)
                {
                    digit = (char)('0' + remainder);
                }
                else
                {
                    digit = (char)('A' + remainder - 10);
                }
                result = digit + result;
                decimalNum = decimalNum / baseNum;
            }
            return result;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtDecimal.Clear();
            txtBase.Clear();
            txtResult.Clear();
        }

    }
}
